import json
import re
import logging
from django import http
from django.contrib.auth import login, logout, authenticate
from django.db import DatabaseError
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.generic.base import View
from django_redis import get_redis_connection
from .models import Users
from PAA_Mange.utils.exceptions import Forbbiden
import json

# Create your views here.
class EmailView(View):
    def post(self,requests):
        '''
        保存当前用户邮箱地址
        :param requests:
        :return:
        '''
        # 接收数据
        params = requests.body.decode()
        dict_params = json.loads(params)
        # 校验参数
        if not params:
            return JsonResponse({'code': 500, 'errormsg': '缺少必传参数'})
        # 保存数据
        count = Users.objects.filter(id=dict_params['userid']).update(email=dict_params['email'])
        # 相应结果
        if count>0:
            return JsonResponse({'code':'200'})
        return JsonResponse({'code': 500, 'errormsg': 'Error'})
class UserCenterView(View):
    '''显示个人信息中心'''
    def get(self,requests):
        # return render(requests, 'userapp/user_center.html')
        if requests.user.is_authenticated:
            return render(requests,'userapp/user_center.html')
        else:
            return redirect(reverse('newsapp:index'))
class LoginView(View):
    def get(self,request):
        '''显示登录界面'''
        return render(request,'userapp/login.html')
    def post(self,request):
        '''处理登录功能'''
        # 获取参数
        username = request.POST.get('username','')
        password = request.POST.get('password','')
        remember = request.POST.get('remember','')
        # 校验参数是非为空
        if not all([username,password]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 校验参数格式
        # if not re.match(r'^[a-zA-Z][a-zA-Z0-9_]{4,7}$',username):
        #     return http.HttpResponseForbidden('请输入5-8字符的用户名')
        if not re.match(r'^[0-9a-zA-Z]{3,8}$',password):
            return http.HttpResponseForbidden('请输入3-8位的密码')
        # 用户密码是否正确
        user = authenticate(username=username,password=password)
        if user is None:
            return render(request,'userapp/login.html',)
        # 保持登录态
        login(request=request,user=user)
        if remember!='on':
            # 如果没记住密码则浏览器关闭则退出
            request.session.set_expiry(0)
        else:
            # None为十四天有效期
            request.session.set_expiry(None)
        return redirect(reverse('newsapp:index'))
class RegisterView(View):
    def get(self,request):
        return render(request,'userapp/register.html')


    def post(self,request):
        '''注册账号'''
        # 接收参数
        username = request.POST.get('username','')
        phone =request.POST.get('phone','')
        password =request.POST.get('password','')
        code =request.POST.get('code','')
        # 校验参数
        if not all([username,password,phone]):
            raise Forbbiden('缺少必传参数')
            # return JsonResponse({'code': '4001','errormsg':'缺少必传参数'})
        if not re.match(r'^[a-zA-Z][a-zA-Z0-9_]{4,7}$',username):
            raise Forbbiden('请输入5-8字符的用户名')
        if not re.match(r'^[0-9a-zA-Z]{3,8}$',password):
            raise Forbbiden('请输入3-8位的密码')
        if not re.match(r'^1[3589]\d{9}$',phone):
            raise Forbbiden('请输入正确的手机号码')
        # redis_conn = get_redis_connection('verify_code')
        # print(redis_conn.decode('utf-8'))

        # 保存注册数据
        try:
            user = Users.objects.create_user(username=username,password=password,phone=phone)
        except DatabaseError:
            return render(request,'userapp/register.html',{'reg_error_msg':'注册失败'})
        # 状态保持
        login(request,user)
        # 返回相应结果

        return redirect(reverse('newsapp:index'))



class UsernaemCount(View):
    def get(self,request,username):
        '''
        查询当前用户名的记录数
        :param request:
        :param username:
        :return:
        '''
        count = Users.objects.filter(username=username).count()
        return JsonResponse({'code':200,'errormsg':'ok','count':count})


class logoutView(View):
    def get(self,request):
        '''
        用户退出登录
        :param request:
        :return:
        '''
        logout(request)
        return redirect(reverse('newsapp:index'))



class PhoneCount(View):
    def get(self,request,phone):
        '''
        查询当前手机号是否使用
        :param request:
        :param phone:
        :return:
        '''
        count = Users.objects.filter(phone=phone).count()
        return JsonResponse({'code':200,'errormsg':'ok','count':count})
#
